<?php

require(WEB_SERVER_ROOT_PATH. 'lib/push/RequestCore.lib.php');

class Jpush {
	private $_masterSecret = '';
	private $_appkeys = '';
	private $diaryListCacheModel;
	
	/**
	 * 构造函数
	 * @param string $username
	 * @param string $password
	 * @param string $appkeys
	 */
	function __construct($masterSecret = '69c0888804a53e4d822af3b3',$appkeys = '6289c70c75dda4a2e4b66231') {
		$this->_masterSecret = $masterSecret;
		$this->_appkeys = $appkeys;
		$this->diaryListCacheModel  =	new DiaryListCacheModel();
	}

    //推送android设备消息
    public function baiduPushAnd($param, $user_id, $deviceSN)
    {
        $channel = new Channel (AC::$baidu_apiKey, AC::$baidu_secretKey) ;

        // 单个为1,tag为2,全部为3
        $push_type = 1;
        $optional[Channel::USER_ID]      = $user_id;
        $optional[Channel::DEVICE_TYPE]  = 3;
        $optional[Channel::MESSAGE_TYPE] = 0;
        //通知类型的内容必须按指定内容发送，示例如下：
        $data = array();
        $data['title']   = '粉粉日记';
        $extra 			 = $param['data'];
	
        # 截取字符串
        $array = self::my_json_encode($extra);
        $len   = strlen($array);
        $limit = 1000-$len;
        $data['content'] = UK::getstr($param['content'], $limit, '...');
        $data['extras'] = $extra;
        $message = UK::var_json_encode($data);
        
        $message_key = $user_id.substr(AC::SERVER_TIME, 5);

        if (AC::PUSH_TO_REDIS) {
            Jpush::addPushDataToRedisList($push_type, $message, $message_key, $optional);
        }else{
            $channel->pushMessage ( $push_type, $message, $message_key, $optional ) ;
        }
        
        return TRUE;
    }
	
    //推送ios设备消息
    public function baiduPushIos($param, $user_id, $deviceSN, $baidu_key_ios_2 = '', $baidu_secretKey_ios_2 = '', $plantform = '')
    {
        $channel = new Channel ($baidu_key_ios_2, $baidu_secretKey_ios_2) ;
        
        $push_type = 1;
        $optional[Channel::USER_ID]      = $user_id;
        $optional[Channel::DEVICE_TYPE]  = 4;
        $optional[Channel::MESSAGE_TYPE] = 1;
        $optional[Channel::DEPLOY_STATUS] = 2;
        
        $extra = array(
                'uid'    =>    $param['data']['uid'],
                'fUid'   =>    $param['data']['fromUid'],
                'type'   =>    $param['data']['type'],
                'mTimes' =>    $param['data']['messageTimes'],
                'eType'  =>    $param['data']['eventType'],
                'eGid'   =>    $param['data']['eventTypeGid']
        );
        $sound = 'default';
        
        # 截取字符串
        $array = self::my_json_encode($extra);
    	$len   = strlen($array);
    	$limit = 180-$len;
        $content = UK::getstr($param['content'], $limit, '...');
        $message = array(
                "aps" => array(
                        "alert" => $content,
                        "badge" => AC::$closeBdMsgpushVersion ? intval($extra['mTimes']) : 1,
                        "sound" => $sound,
                ),
                "extras" => $extra
        );
        
        $message_key = $user_id.substr(AC::SERVER_TIME, 5);

        if (AC::PUSH_TO_REDIS) {
            Jpush::addPushDataToRedisList($push_type, $message, $message_key, $optional, $plantform);
        }else{
            $channel->pushMessage ( $push_type, $message, $message_key, $optional ) ;
        }
         
        return TRUE;
    }
    
    /**
     * 百度tag推送
     * @param unknown $param
     * @return Ambigous <成功：PHP数组；失败:false, boolean, mixed>
     */
    public function baiduTagPush($param, $baidu_key_ios_2 = '', $baidu_secretKey_ios_2 = '')
    {
        $channel = new Channel (AC::$baidu_apiKey, AC::$baidu_secretKey) ;
        $push_type = 2;
        $tag_name  = "chatgroup_".$param['extras']['gid'];
        $optional[Channel::TAG_NAME]     = $tag_name;
        $optional[Channel::DEVICE_TYPE]  = 3;
        $optional[Channel::MESSAGE_TYPE] = 0;

        // 安卓
        $data = array();
        $extra           = $param['extras'];
        $gname           = $extra['name'];
        $data['title']   = $gname;
        unset($extra['name']);
        $message_key     = $tag_name.substr(AC::SERVER_TIME, 5);
        
        $array = self::my_json_encode($extra);
        $len   = strlen($array);
        $limit = 1000-$len;
        $data['content'] = UK::getstr($param['content'], $limit, '...');
        $data['extras'] = $extra;
        $message = UK::var_json_encode($data);
        
        if (AC::PUSH_TO_REDIS) {
            Jpush::addPushDataToRedisList($push_type, $message, $message_key, $optional);
        }else{
            $channel->pushMessage ( $push_type, $message, $message_key, $optional ) ;
        }
        
        // ios
        $channel = new Channel ($baidu_key_ios_2, $baidu_secretKey_ios_2) ;
        $data['title']   = '粉粉日记';
        $optional[Channel::DEVICE_TYPE]  = 4;
        $optional[Channel::MESSAGE_TYPE] = 1;
        $limit = 180-$len;
        $data['content'] = UK::getstr($param['content'], $limit, '...');
        $message = array(
                "aps" => array(
                        "alert" => $data['content'],
                        "badge" => 1,
                        "sound" => 'default',
                ),
                "extras" => $extra
        );
        
        if (AC::PUSH_TO_REDIS) {
            Jpush::addPushDataToRedisList($push_type, $message, $message_key, $optional, 'ios');
        }else{
            $channel->pushMessage ( $push_type, $message, $message_key, $optional ) ;
        }
        
        return TRUE;
    }
    
    private function addPushDataToRedisList ($push_type, $message, $message_key, $optional, $platform = 'android') {
        // 异步
        global $_G;
        $host_name = empty($_G['serverHost']) ? "na" : $_G['serverHost'];
        $pushData = array(
            'push_type' =>  $push_type,
            'message'   =>  $message,
            'message_key'   =>  $message_key,
            'optional'      =>  $optional,
            'platform'      =>  $platform,
            'source'        =>  $host_name
        );

        $diaryListCache = new DiaryListCacheModel();
        return $diaryListCache->addPushToList(json_encode($pushData));
    }
	
    /**
     * json格式转换
     * @param array $arr
     */
    private function my_json_encode($in)/*{{{*/
    {
    	$_escape = function ($str) {
    		return addcslashes($str, "\v\t\n\r\f\"\\/");
    	};
    	$out = "";
    	if (is_object($in)) {
    		$class_vars = get_object_vars(($in));
    		$arr = array();
    		foreach ($class_vars as $key => $val) {
    			$arr[$key] = "\"{$_escape($key)}\":\"{$val}\"";
    		}
    		$val = implode(',', $arr);
    		$out .= "{{$val}}";
    	}elseif (is_array($in)) {
    		$obj = false;
    		$arr = array();
    		foreach($in AS $key => $val) {
    			if(!is_numeric($key)) {
    				$obj = true;
    			}
    			$arr[$key] = self::my_json_encode($val);
    		}
    		if($obj) {
    			foreach($arr AS $key => $val) {
    				$arr[$key] = "\"{$_escape($key)}\":{$val}";
    			}
    			$val = implode(',', $arr);
    			$out .= "{{$val}}";
    		}else {
    			$val = implode(',', $arr);
    			$out .= "[{$val}]";
    		}
    	}elseif (is_bool($in)) {
    		$out .= $in ? 'true' : 'false';
    	}elseif (is_null($in)) {
    		$out .= 'null';
    	}elseif (is_string($in)) {
    		$out .= "\"{$_escape($in)}\"";
    	}else {
    		$out .= $in;
    	}
    	return "{$out}";
    }/*}}}*/

	/**
	 * 模拟post进行url请求
	 * @param string $url
	 * @param string $param
	 */
	function request_post($url = '', $param = '') {
		if (empty($url) || empty($param)) {
			return false;
		}
		
		$postUrl = $url;
		$curlPost = $param;
		$ch = curl_init();//初始化curl
		curl_setopt($ch, CURLOPT_URL,$postUrl);//抓取指定网页
		curl_setopt($ch, CURLOPT_HEADER, 0);//设置header
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);//要求结果为字符串且输出到屏幕上
		curl_setopt($ch, CURLOPT_POST, 1);//post提交方式
		curl_setopt($ch, CURLOPT_POSTFIELDS, $curlPost);
		$data = curl_exec($ch);//运行curl
		curl_close($ch);
		
		return $data;
	}
	/**
	 * 发送
	 * @param int $sendno 发送编号。由开发者自己维护，标识一次发送请求
	 * @param int $receiver_type 接收者类型。1、指定的 IMEI。此时必须指定 appKeys。2、指定的 tag。3、指定的 alias。4、 对指定 appkey 的所有用户推送消息。
	 * @param string $receiver_value 发送范围值，与 receiver_type相对应。 1、IMEI只支持一个 2、tag 支持多个，使用 "," 间隔。 3、alias 支持多个，使用 "," 间隔。 4、不需要填
	 * @param int $msg_type 发送消息的类型：1、通知 2、自定义消息
	 * @param string $msg_content 发送消息的内容。 与 msg_type 相对应的值
	 * @param string $platform 目标用户终端手机的平台类型，如： android, ios 多个请使用逗号分隔
	 * @param int $time 保存离线的时长,默认为保存1天的离线消息（86400秒）
	 */
	public static function send($sendno,$receiver_type, $receiver_value, $msg_type = 1, $msg_content , $platform, $time = 86400) {
		$url = 'http://api.jpush.cn:8800/v2/push';
		$param = '';		
		$param .= '&sendno='.$sendno;
		$jpush  =  new Jpush();	
		$appkeys = $jpush->_appkeys;				
		$param .= '&app_key='.$appkeys;	
		$param .= '&receiver_type='.$receiver_type;				
		$param .= '&receiver_value='.$receiver_value;
		$masterSecret = $jpush->_masterSecret;
		$verification_code = md5($sendno.$receiver_type.$receiver_value.$masterSecret);				
		$param .= '&verification_code='.$verification_code;			
		$param .= '&msg_type='.$msg_type;			
		$param .= '&msg_content='.$msg_content;		
		$param .= '&platform='.$platform;	
		$param .= '&time_to_live='.$time;
		
		$res = $jpush->request_post($url, $param);
		$res_arr = json_decode($res, true);	
	    return intval($res_arr['errcode']);
	}
	
}

?>